<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use Auth;
class UsersController extends Controller
{

    //构造函数 权限认证
   public  function __construct()
   {
       $this->middleware('auth',[
         'except'=>['show', 'create', 'store','index'],
       ]);
      $this->middleware('guest',[
         'only'=>['create'],
     ]);
   }
   //所有用户
   public function index()
  {
    $users=User::paginate(8);
    return view("users.index",compact("users"));
  }

  public function create()
  {



    return view('users.create');
  }
    //展示页
    public function show(User $user)
    {


     return view('users.show',compact("user"));
    }
    //验证并存储
    public function store(Request $request)
    {
          $this->validate($request,[
           "name"=>"required|max:10",
           "email"=>"required|email|unique:users|max:20",
           "password"=>"required|confirmed|min:6"

          ]);
          //User::create([])创建
          $user = User::create([
               'name' => $request->name,
               'email' => $request->email,
               'password' => bcrypt($request->password),
           ]);
           Auth::login($user);
           session()->flash('success', '欢迎，您将在这里开启一段新的旅程~');
         return redirect()->route('users.show', [$user]);
    }

    //修改更新操作
    public function edit(User $user)
    {
       $this->authorize('update',$user);
       return view('users.edit',compact("user"));
    }

    public function update(User $user,Request $request)
    {
      $this->validate($request,[
         'name'=>'required|max:10',
         'password' => 'nullable|confirmed|min:6',
      ]);
      $this->authorize('update',$user);
      $data=[];
      $data['name']=$request->name;
      if($request->password){
         $data['password']=bcrypt($request->password);
      }
      $user->update($data);
      session()->flash('success',"个人资料更新成功");
     return redirect()->route('users.show',$user->id);
    }

}
